<?php

class Notification extends \Phalcon\Mvc\Model
{

    /**
     *
     * @var integer
     */
    public $id;

    /**
     *
     * @var integer
     */
    public $receiver_id;

    /**
     *
     * @var string
     */
    public $type;

    /**
     *
     * @var string
     */
    public $date_created;

    /**
     *
     * @var integer
     */
    public $has_read;

    /**
     *
     * @var string
     */
    public $params;

    /**
     * Independent Column Mapping.
     */
    public function columnMap()
    {
        return array(
            'id' => 'id', 
            'receiver_id' => 'receiver_id', 
            'type' => 'type', 
            'date_created' => 'date_created', 
            'has_read' => 'has_read', 
            'params' => 'params'
        );
    }

    public function countUnread($receiver_id)
    {
        $phql = "SELECT COUNT(id) AS TOTAL FROM Notification
                 WHERE receiver_id = ?0 and has_read = 0";
        $data = $this->modelsManager->executeQuery($phql,array(0=>$receiver_id));
        return $data[0]->TOTAL;
    }
    public function saveRequest($receiver_id,$params)
    {
        $notif = new Notification();
                $notif->type = "accept_request";
                $notif->receiver_id = $receiver_id;
                $notif->params = json_encode($params);
        return @$notif->save();
    }
    public function saveGroupRequest($receiver_id,$params)
    {
        $notif = new Notification();
                $notif->type = "accept_group_request";
                $notif->receiver_id = $receiver_id;
                $notif->params = json_encode($params);
        return @$notif->save();   
    }

    public function saveWallPost($receiver_id,$params)
    {
        $notif = new Notification();
                $notif->type = "wall_post";
                $notif->receiver_id = $receiver_id;
                $notif->params = json_encode($params);
        return @$notif->save();
    }

    public function saveComment($receiver_id,$params)
    {
        $notif = new Notification();
                $notif->type = "comment";
                $notif->receiver_id = $receiver_id;
                $notif->params = json_encode($params);
        return @$notif->save();
    }

    public function beforeValidationOnCreate()
    {
        $this->date_created = CURR_DATE;
        $this->has_read = 0;
    }

    public function listNotification($receiver_id)
    {
        $phql = "SELECT nit.*,uat.* FROM Notification nit 
                 LEFT JOIN UserAccountTb uat on uat.id = nit.receiver_id
                 WHERE nit.receiver_id = ?0 
                 ORDER BY nit.date_created DESC";
        $data = $this->modelsManager->executeQuery($phql,array(0=>$receiver_id));
        return @$data;
    }

}
